<template>
  <view class="feedback-container">
    <!-- 顶部栏：动态标题 -->
    <view class="top-bar">
      <view class="back-btn" @click="gotoPersonalCenter">
        <image
            class="back-icon"
            src="/static/icons/back-arrow.png"
            mode="aspectFit"
        />
      </view>
      <view class="page-title">{{ pageTitle }}</view>

      <!-- 仅在非查看模式下显示“反馈历史”图标 -->
      <view class="action-icons" v-if="!isViewing">
        <image
            class="history-icon"
            src="/static/icons/feedback-history.png"
            mode="aspectFit"
            @click="gotoFeedbackList"
        />
      </view>
    </view>

    <!-- 问题标题：根据模式设置 disabled -->
    <view class="form-section">
      <view class="label">问题标题</view>
      <input
          v-model="feedbackTitle"
          class="title-input"
          placeholder="请输入问题标题（最多30字）"
          maxlength="30"
          :disabled="isViewing"
      />
      <view class="title-count">{{ feedbackTitle.length }}/30</view>
    </view>


    <!-- 问题分类：查看和编辑模式只读，仅新建模式可选择 -->
    <view class="form-section">
      <view class="label">问题分类</view>
      <!-- 仅新建模式：可选择 -->
      <view class="category-list" v-if="!isViewing && !isEditing">
        <view
            v-for="(item, index) in categories"
            :key="index"
            class="category-item"
            :class="{ 'active': currentCategory === index }"
            @click="currentCategory = index"
        >
          {{ item }}
        </view>
      </view>
      <!-- 查看模式：只读显示 -->
      <view class="category-view" v-else-if="isViewing">
        <text>{{ displayCategory }}</text>
      </view>
      <!-- 编辑模式：只读显示 -->
      <view class="category-view" v-else>
        <text>{{ displayCategory }}</text>
      </view>
    </view>

    <!-- 反馈内容：根据模式设置 disabled -->
    <view class="form-section">
      <view class="label">反馈内容</view>
      <textarea
          v-model="feedbackContent"
          class="content-textarea"
          placeholder="请输入您的反馈内容，最多300字"
          maxlength="300"
          :disabled="isViewing"
      ></textarea>
      <view class="content-count">{{ feedbackContent.length }}/300</view>
    </view>

    <!-- 图片上传：查看模式下不显示“+”按钮和删除图标 -->
    <view class="form-section">
      <view class="label">上传图片</view>
      <view class="image-list">
        <view
            v-for="(url, idx) in imageUrls"
            :key="idx"
            class="image-item"
        >
          <image :src="url" class="image-preview" mode="widthFix" />
          <view class="delete-icon" @click.stop="deleteImage(idx)" v-if="!isViewing">×</view>
        </view>
        <view
            v-if="imageUrls.length < 5 && !isViewing"
            class="add-image"
            @click="chooseImage"
        >
          +
        </view>
      </view>
    </view>

    <!-- 回复内容区域（查看模式且有回复时显示） -->
    <view v-if="isViewing && (currentFeedback?.reply || currentFeedback?.replyImages?.length)" class="form-section reply-section">
      <view class="label">客服回复</view>
      <view class="reply-content" v-if="currentFeedback.reply">
        <text>{{ currentFeedback.reply }}</text>
      </view>
      <view class="reply-images" v-if="currentFeedback.replyImages && currentFeedback.replyImages.length">
        <view
            v-for="(url, idx) in currentFeedback.replyImages"
            :key="idx"
            class="image-item"
        >
          <image :src="url" class="image-preview" mode="widthFix" />
        </view>
      </view>
    </view>

    <!-- 提交/更新按钮：仅在非查看模式下显示 -->
    <button
        class="submit-btn"
        :disabled="!feedbackTitle.trim() || !feedbackContent || feedbackContent.trim().length === 0 || isSubmitting || isSubmitted"
        @click="handleSubmit"
        v-if="!isViewing"
    >
      {{ isSubmitting ? (isEditing ? '更新中...' : '提交中...') : (isSubmitted ? (isEditing ? '已更新' : '已提交') : (isEditing ? '更新反馈' : '提交反馈')) }}
    </button>
  </view>
</template>

<script setup>
import { ref, onUnmounted, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import request from '@/utils/request.js';

// 防抖动函数
const debounce = (fn, delay = 500) => {
  let timer = null;
  return function (...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
};

// 状态管理
const isEditing = ref(false);
const isViewing = ref(false); // 新增：判断是否为查看模式
const currentFeedback = ref(null);
const feedbackId = ref('');
const categories = ref([]);
const currentCategory = ref(0);
const feedbackTitle = ref('');
const feedbackContent = ref(''); // 确保初始为字符串
const imageUrls = ref([]);
const isSubmitting = ref(false);
const isSubmitted = ref(false);

// 动态页面标题
const pageTitle = computed(() => {
  if (isViewing.value) return '反馈详情';
  if (isEditing.value) return '编辑反馈';
  return '我要反馈';
});

// 显示的分类文本 (处理新建和编辑/查看模式)
const displayCategory = computed(() => {
  if (currentFeedback.value && currentFeedback.value.category) {
    return currentFeedback.value.category;
  }
  if (categories.value.length > 0) {
    return categories.value[currentCategory.value];
  }
  return '';
})

// 页面加载逻辑
onLoad(async (options) => {
  // 1. 获取反馈分类
  try {
    const res = await request.get('agent/feedback/categories');
    // 业务状态码判断：仅code=200时处理分类数据
    if (res.code === 200) {
      categories.value = res.data || [];
    } else {
      uni.showToast({ title: res.msg || '获取分类失败', icon: 'none' });
    }
  } catch (error) {
    console.error('获取分类失败:', error);
    uni.showToast({ title: '网络异常，请稍后再试', icon: 'none' });
  }

  // 2. 检查路由参数（查看/编辑反馈）
  if (options.feedbackId) {
    feedbackId.value = options.feedbackId;

    // 根据 mode 参数判断是查看还是编辑
    if (options.mode === 'view') {
      isViewing.value = true;
    } else if (options.mode === 'edit') {
      isEditing.value = true;
    }

    // 3. 获取反馈详情
    try {
      const res = await request.get(`agent/feedback/queryDetail?id=${feedbackId.value}`);
      // 业务状态码判断：仅code=200时处理详情数据
      if (res.code === 200) {
        currentFeedback.value = res.data;
        feedbackTitle.value = currentFeedback.value.title ? String(currentFeedback.value.title) : '';
        feedbackContent.value = currentFeedback.value.content ? String(currentFeedback.value.content) : '';
        imageUrls.value = currentFeedback.value.images || [];

        // 编辑模式下，自动选中对应分类的索引
        if (isEditing.value && categories.value.length > 0) {
          const categoryIndex = categories.value.findIndex(item => item === currentFeedback.value.category);
          if (categoryIndex !== -1) {
            currentCategory.value = categoryIndex;
          }
        }
      } else {
        uni.showToast({ title: res.msg || '获取反馈详情失败', icon: 'none' });
        setTimeout(() => uni.navigateBack(), 1500);
      }
    } catch (error) {
      console.error('获取反馈详情失败:', error);
      uni.showToast({ title: '网络异常，请稍后再试', icon: 'none' });
      setTimeout(() => uni.navigateBack(), 1500);
    }
  }
});

// 页面卸载前检查
onUnmounted(() => {
  if (isSubmitting.value && !isSubmitted.value) {
    uni.showToast({ title: '操作未完成，请勿重复提交', icon: 'none', duration: 1500 });
  }
});

// 选择图片并上传
const chooseImage = async () => {
  const maxCount = 5 - imageUrls.value.length;
  if (maxCount <= 0) return;

  try {
    const res = await uni.chooseImage({
      count: maxCount,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera']
    });

    if (res.tempFilePaths && res.tempFilePaths.length > 0) {
      const uploadPromises = res.tempFilePaths.map(tempPath =>
          request.upload('agent/file/upload', tempPath, 'files')
      );

      const uploadResults = await Promise.all(uploadPromises);
      uploadResults.forEach(urlsArray => {
        if (urlsArray && urlsArray.length > 0) {
          imageUrls.value.push(...urlsArray);
        }
      });
    }
  } catch (error) {
    console.error('图片上传失败:', error);
    uni.showToast({ title: '图片上传失败，请重试', icon: 'none' });
  }
};

// 删除图片
const deleteImage = (index) => {
  imageUrls.value.splice(index, 1);
};

// 跳转到反馈列表
const gotoFeedbackList = () => {
  uni.navigateTo({ url: '/pages/feedback/list' });
};

// 跳转到个人中心
const gotoPersonalCenter = () => {
  uni.navigateTo({ url: '/pages/user/index' });
};

// 提交逻辑
const submitAction = async () => {
  // 判空逻辑优化：先检查标题和内容
  if (!feedbackTitle.value.trim() || !feedbackContent.value || feedbackContent.value.trim().length === 0 || isSubmitting.value || isSubmitted.value) {
    uni.showToast({ title: '标题和内容不能为空', icon: 'none' });
    return;
  }

  const feedbackData = {
    title: feedbackTitle.value,
    content: feedbackContent.value,
    images: imageUrls.value
  };

  try {
    isSubmitting.value = true;
    let res;

    // 编辑模式：调用更新接口
    if (isEditing.value) {
      feedbackData.id = feedbackId.value;
      res = await request.put('agent/feedback/update', feedbackData);
    }
    // 新建模式：调用提交接口
    else {
      feedbackData.category = categories.value[currentCategory.value];
      res = await request.post('agent/feedback/submit', feedbackData);
    }

    // 业务状态码判断：仅code=200时视为操作成功
    if (res.code === 200) {
      isSubmitted.value = true;
      const successText = res.msg || (isEditing.value ? '更新成功' : '提交成功');

      uni.showToast({ title: successText, icon: 'success', duration: 1500 });
      uni.$emit('refreshFeedbackList');

      // 跳转反馈列表
      setTimeout(() => {
        uni.navigateTo({
          url: '/pages/feedback/list',
          success: () => {
            uni.$emit('refreshFeedbackList');
            // 重置表单状态
            feedbackTitle.value = '';
            feedbackContent.value = '';
            imageUrls.value = [];
            currentCategory.value = 0;
            isSubmitting.value = false;
          }
        });
      }, 1500);
    } else {
      // 业务错误：显示后端返回的错误信息
      uni.showToast({ title: res.msg || '操作失败', icon: 'none' });
      isSubmitting.value = false;
    }
  } catch (error) {
    // 网络异常：显示通用提示
    console.error('提交/更新反馈失败:', error);
    uni.showToast({ title: '网络异常，请稍后再试', icon: 'none' });
    isSubmitting.value = false;
  }
};

// 防抖动包装提交方法
const handleSubmit = debounce(submitAction, 800);
</script>

<style scoped>
.feedback-container {
  width: 100%;
  min-height: 100vh;
  background-color: #fff;
  padding: 20px;
  box-sizing: border-box;
}

.top-bar {
  display: flex;
  align-items: center;
  margin-bottom: 25px;
}

.back-btn {
  margin-right: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.back-icon {
  width: 24px;
  height: 24px;
}

.page-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  flex: 1;
  text-align: center;
}

.action-icons {
  margin-left: auto;
}

.history-icon {
  width: 24px;
  height: 24px;
  cursor: pointer;
}

.title-input {
  width: 100%;
  height: 40px;
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 0 15px;
  box-sizing: border-box;
  font-size: 14px;
  color: #333;
}
.title-input:focus {
  outline: none;
  border-color: #409eff;
}
.title-count {
  text-align: right;
  font-size: 12px;
  color: #999;
  margin-top: 8px;
}

/* 分类列表样式 */
.category-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 8px;
}
.category-item {
  padding: 8px 15px;
  border: 1px solid #ddd;
  border-radius: 20px;
  font-size: 14px;
  color: #666;
  transition: all 0.2s;
}
.category-item.active {
  background-color: #409eff;
  color: #fff;
  border-color: #409eff;
}

/* 分类查看样式 */
.category-view {
  padding: 10px;
  background-color: #f7f7f7;
  border-radius: 8px;
  color: #333;
  font-size: 14px;
  margin-top: 8px;
}

.content-textarea {
  width: 100%;
  min-height: 150px;
  border: 1px solid #ddd;
  border-radius: 12px;
  padding: 15px;
  box-sizing: border-box;
  font-size: 14px;
  color: #333;
  resize: none;
  overflow-y: auto;
}
.content-textarea:focus {
  outline: none;
  border-color: #409eff;
}
.content-count {
  text-align: right;
  font-size: 12px;
  color: #999;
  margin-top: 8px;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}
.image-item {
  width: calc((100% - 30px) / 4);
  position: relative;
}
.image-preview {
  width: 100%;
  height: 80px;
  border-radius: 8px;
  object-fit: cover;
  border: 1px solid #eee;
}
.delete-icon {
  position: absolute;
  top: -5px;
  right: -5px;
  width: 20px;
  height: 20px;
  background-color: rgba(255, 50, 50, 0.9);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
.add-image {
  width: calc((100% - 30px) / 4);
  height: 80px;
  border: 1px dashed #ddd;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 30px;
  color: #ddd;
}

/* 回复区域样式 */
.reply-section {
  margin-top: 20px;
}
.reply-content {
  padding: 10px;
  background-color: #f0f9ff;
  border-radius: 8px;
  color: #333;
  font-size: 14px;
  margin-top: 5px;
  line-height: 1.6;
}
.reply-images {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}

.submit-btn {
  width: 100%;
  height: 48px;
  background-color: #409eff;
  color: #fff;
  border-radius: 24px;
  font-size: 16px;
  margin-top: 20px;
  line-height: 1.5;
}
.submit-btn:disabled {
  background-color: #b3d8ff;
  color: #fff;
}
</style>